package mju.cxf.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import mju.cxf.constant.MessageConstant;
import mju.cxf.context.BaseContext;
import mju.cxf.dto.CreateOrderDTO;
import mju.cxf.dto.UserLoginDTO;
import mju.cxf.entity.*;
import mju.cxf.exception.BaseException;
import mju.cxf.result.Result;
import mju.cxf.service.*;
import mju.cxf.vo.OrderListVO;
import mju.cxf.vo.SalesKeyVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Api(tags = "订单相关接口列表")
@RequestMapping("/user/api/order")
public class IOrderController {
    @Autowired
    private ProductSpecificationsService productSpecificationsService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private CommentsService commentsService;
    @Autowired
    private IntegralService integralService;

    /**
     * U新增订单
     *
     * @param createOrderDTO 订单信息
     * @return 是否成功
     */
    @PostMapping("/create")
    @ApiOperation(value = "新增订单", notes = "点击购买后新增订单")
    public Result<Object> createOrder(@RequestBody CreateOrderDTO createOrderDTO) {
        ProductSpecifications goods = createOrderDTO.getGoods();
        double orderPrice = goods.getPrice() * createOrderDTO.getNumber();
        //会员抵扣
        final User user = userService.getById(BaseContext.getCurrentId());
        if (user == null) {
            throw new BaseException(MessageConstant.SERVICE_ERROR);
        }
        final Double member = user.getMember();
        double memberPrice = 0.00;
        if (member > 100 && member <= 1000) {
            memberPrice = orderPrice * 0.10;
            String formattedMemberPrice = String.format("%.2f", memberPrice);  // 保留两位小数
            memberPrice = Double.valueOf(formattedMemberPrice);
        } else if (member > 1000) {
            memberPrice = orderPrice * 0.30;
            String formattedMemberPrice = String.format("%.2f", memberPrice);  // 保留两位小数
            memberPrice = Double.valueOf(formattedMemberPrice);
        }
        //积分抵扣
        BigDecimal pointsPrice = new BigDecimal(createOrderDTO.getPointsNumber()).divide(new BigDecimal(1000), 2, RoundingMode.HALF_UP);
        double pointsPriceDouble = pointsPrice.doubleValue();

        Order order = Order.builder()
                .creationTime(LocalDateTime.now())
                .userId(BaseContext.getCurrentId())
                .productId(goods.getId())
                .status(0)
                .integralPrice(pointsPriceDouble)
                .orderPrice(orderPrice)
                .memberPrice(memberPrice)
                .amount((orderPrice - memberPrice) - pointsPriceDouble)
                .quantity(createOrderDTO.getNumber())
                .number("XSDD" + System.currentTimeMillis())
                .build();
        if (orderService.createOrder(order)) {
            if (user.getPoints() < createOrderDTO.getPointsNumber()) {
                throw new BaseException(MessageConstant.SERVICE_ERROR);
            }
            user.setPoints(user.getPoints() - createOrderDTO.getPointsNumber());
            userService.updateById(user);
            if (createOrderDTO.getPointsNumber() > 0) {
                final Integral integral = Integral.builder()
                        .createTime(LocalDateTime.now())
                        .type(1)
                        .userId(BaseContext.getCurrentId())
                        .tittle("订单积分抵扣")
                        .number(-createOrderDTO.getPointsNumber()).build();
                integralService.save(integral);
            }
            return Result.success(orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getNumber, order.getNumber())));
        }
        return Result.error(MessageConstant.FAILURE_MESSAGE);
    }

    /**
     * 查询所有订单
     *
     * @return 所有订单信息
     */
    @GetMapping("/page")
    @ApiOperation(value = "查看订单列表", notes = "点击订单后查询订单详情信息")
    public Result<HashMap<String, Object>> orderAll(@RequestParam("page") int page,
                                                    @RequestParam("size") int size) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        //根据创建时间倒叙
        queryWrapper.orderByDesc(Order::getCreationTime).eq(Order::getUserId, BaseContext.getCurrentId());
        Page<Order> page1 = orderService.page(new Page<>(page, size), queryWrapper);
        final List<OrderListVO> orderListVOS = page1.getRecords().stream().map((order) -> {
            final ProductSpecifications productSpecifications = productSpecificationsService.getById(order.getProductId());
            int endTime = order.getStatus() == 0 ?
                    (int) ((300 - (System.currentTimeMillis() - order.getCreationTime()
                            .atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()) / 1000) + 1) : 0;
            if (endTime < 0) {
                endTime = 0;
                //取消订单
                orderService.deleteIntegralNumber(order);

            }
            LambdaQueryWrapper<Comments> cqw = new LambdaQueryWrapper<>();
            cqw.eq(Comments::getProductId, order.getProductId()).eq(Comments::getUserId, BaseContext.getCurrentId());
            return OrderListVO.builder()
                    .productSpecifications(productSpecifications)
                    .order(order)
                    .endTime(endTime)
                    .build();
        }).collect(Collectors.toList());
        HashMap<String, Object> map = new HashMap<>();
        map.put("orderListVOS", orderListVOS);
        map.put("pages", page1.getPages());
        map.put("current", page1.getCurrent());
        return Result.success(map);
    }

    /**
     * 查询订单详情
     *
     * @return 订单详情信息
     */
    @PostMapping("/detail")
    @ApiOperation(value = "查看订单详情", notes = "点击订单后查询订单详情信息")
    public Result<OrderListVO> orderDetail(@RequestBody int id) {
        final Order orderById = orderService.getById(id);
        final ProductSpecifications productSpecificationsById = productSpecificationsService.getById(orderById.getProductId());
        int endTime = orderById.getStatus() == 0 ?
                (int) ((300 - (System.currentTimeMillis() - orderById.getCreationTime()
                        .atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()) / 1000) + 1) : 0;
        return Result.success(OrderListVO.builder()
                .productSpecifications(productSpecificationsById)
                .order(orderById)
                .endTime(endTime)
                .build());
    }

    /**
     * U发送查看key邮箱
     *
     * @param userLoginDto 用户信息
     * @return 返回包含用户信息和 token 的结果
     */
    @PostMapping("/bind")
    @ApiOperation(value = "查看key发送邮箱接口", notes = "用户通过此接口发送查看key邮箱")
    public Result<String> bind(@RequestBody UserLoginDTO userLoginDto) {
        orderService.bind(userLoginDto);
        return Result.success();
    }

    /**
     * 取消订单
     *
     * @param orderId 订单号
     * @return 订单
     */
    @PostMapping("/cancelOrder")
    public Result<String> cancelOrder(@RequestParam("orderId") int orderId) {
        final Order orderServiceById = orderService.getById(orderId);
        if (orderServiceById.getStatus() == 7) {
            return Result.error(MessageConstant.FAILURE_MESSAGE);
        }
        orderService.deleteIntegralNumber(orderServiceById);
        return Result.success();
    }

    @Autowired
    private SalesService salesService;

    /**
     * 售后查看卡密总数
     *
     * @param orderId
     * @return
     */
    @PostMapping("/afterKeyList")
    public Result<List<SalesKeyVO>> cancelOrder(@RequestParam("orderId") String orderId) {
        LambdaQueryWrapper<Sales> slw = new LambdaQueryWrapper<>();
        slw.eq(Sales::getOrderNumber, orderId).eq(Sales::getState,4);
        List<SalesKeyVO> salesList = new ArrayList<>();
        salesService.list(slw).forEach(sales -> {
            salesList.add(SalesKeyVO.builder()
                    .cdKey(sales.getCdKey())
                    .salesNumber(sales.getSalesNumber())
                    .id(sales.getId())
                    .productId(sales.getProductId())
                    .specificationsId(sales.getSpecificationsId())
                    .orderNumber(orderId)
                    .build());
        });
        return Result.success(salesList);
    }
}
